* **************************************************************************** *
* Sierra Leone - Social Signaling and Childhood Immunization
* Table: Balance on Characteristics of Main Analysis Sample
* **************************************************************************** *
/*
** Purpose:  Create Balance Table on Characteristics of Main Analysis Sample

*/
* **************************************************************************** *
* **************************************************************************** *



	use   "${Replicate_SocialSignals_dtaInter}/Balance_ListingSample.dta", clear


	* Drop existing matrices
	cap mat drop _all


	lab var good_memory   "Mother's ability to recall last vaccine"
	lab var mean_distance "Distance to clinic (in miles)"

* --------------------------------------------------------------------------
* Run balance in 2 steps: (1) ttest differences, (2) p-values

	local   ListingVars   = " regular_baby traveled_baby moved_baby deceased_baby "
	local   FollowUpVars  = " proportion_flwup surveyed_flwup a04b_flwup_2 a04b_flwup_1 a04b_flwup_3 a04b_flwup_4 "
	local   AgeCardVars   = " age_listing card "

	local   CardVars      = " quality_card "
	local   MemoryVars    = " good_memory "
	local   DistanceVars  = " mean_distance "
	local   PopVars       = " mean_clinic_pop "
	local   BCGVars       = " bcg_pretrend "
	local   Penta1Vars    = " penta1_pretrend "
	local   Penta2Vars    = " penta2_pretrend "


	local   treatVar      = " intervention_arm "
	local   strataVar     = " strata "
	local   clusterVar    = " clinic_code "
	local   covariates    = " anc2 anc3 anc4 "


	******

	foreach  balanceVar in   quality_card good_memory mean_distance mean_clinic_pop  ///
		 bcg_pretrend bcg_pretrend penta2_pretrend {

	dis    "`balanceVar'"

	if     "`balanceVar'" != "mean_clinic_pop" & "`balanceVar'" !=  "penta2_pretrend" {
	dis  "Wrong"
	}
	else {
	dis  "Right"
	}
	}



* **************************************************************************** *
* 1.) Listing Variables
* **************************************************************************** *

* ---------------------------------------------------------------------------- *
* Compute ttest  mean differences
* ---------------------------------------------------------------------------- *

* (1) ttest mean differences

	preserve

		iebaltab  `ListingVars',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///		
		browse ///
		replace

		drop in 1/3

		gen     count = _n

	* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


	* ---------------------------------------------------------------------------- *
	* Compute ttest p-values
	* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `ListingVars',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'

	restore



	* ---------------------------------------------------------------------------- *
	* Merge ttest differences & p-values
	* ---------------------------------------------------------------------------- *

	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 =  "Observations"         if v1 == "N"
		replace v1 =  "Clinics"              if v1 == "Clusters"

		drop if v1 == "Clinics"

		local    listing_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/listing_balance_`listing_fileNum'.tex") ///
		replace tex nohead noauto

	restore




* **************************************************************************** *
* 2.) Follow-up Variables
* **************************************************************************** *

* ---------------------------------------------------------------------------- *
* Compute ttest  mean differences
* ---------------------------------------------------------------------------- *

	* (1) ttest mean differences

	preserve

		iebaltab  `FollowUpVars',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///
		browse ///
		replace

		drop in 1/3

		gen     count = _n

		* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


* ---------------------------------------------------------------------------- *
* Compute ttest p-values
* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `FollowUpVars',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'
	
	restore



* ---------------------------------------------------------------------------- *
* Merge ttest differences & p-values
* ---------------------------------------------------------------------------- *

	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 = "Observations"         if v1 == "N"
		replace v1 = "Clinics"              if v1 == "Clusters"


		local    followup_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/followup_balance_`followup_fileNum'.tex") ///
		replace tex nohead noauto

	restore



* **************************************************************************** *
* 3.) Age & Vaccine card Ownership
* **************************************************************************** *

* ---------------------------------------------------------------------------- *
* Compute ttest  mean differences
* ---------------------------------------------------------------------------- *

	* (1) ttest mean differences

	preserve

		iebaltab  `AgeCardVars',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///
		browse ///
		replace

		drop in 1/3

		gen     count = _n

		* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


* ---------------------------------------------------------------------------- *
* Compute ttest p-values
* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `AgeCardVars',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'
	restore



* ---------------------------------------------------------------------------- *
* Merge ttest differences & p-values
* ---------------------------------------------------------------------------- *


	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 = "Observations"         if v1 == "N"
		replace v1 = "Clinics"              if v1 == "Clusters"

		drop if v1 == "Clinics"

		local    agecard_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/agecard_balance_`agecard_fileNum'.tex") ///
		replace tex nohead noauto

	restore




* **************************************************************************** *
* 4.) Loop over all remaining variables
* **************************************************************************** *


	local VarList =  " quality_card good_memory mean_distance mean_clinic_pop " + ///
	" bcg_pretrend penta1_pretrend penta2_pretrend "

* ---------------------------------------------------------------------------- *
* Compute ttest  mean differences
* ---------------------------------------------------------------------------- *

	foreach balanceVar of local VarList {

	* (1) ttest mean differences

	preserve

		iebaltab  `balanceVar',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///
		browse ///
		replace

		drop in 1/3

		gen     count = _n

		* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


* ---------------------------------------------------------------------------- *
* Compute ttest p-values
* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `balanceVar',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'

	restore



* ---------------------------------------------------------------------------- *
* Merge ttest differences & p-values
* ---------------------------------------------------------------------------- *

	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 = "Observations"         if v1 == "N"
		replace v1 = "Clinics"              if v1 == "Clusters"

		* Drop all clinic numbers except for Clinic Population & Pre-trends
		dis    "`balanceVar'"

		if     "`balanceVar'" != "mean_clinic_pop" & "`balanceVar'" !=  "penta2_pretrend" {
		drop if v1 == "Clinics"
		}
		else {
		dis  "Right"
		}

		* For Clinic Population drop number of observations:
		if     "`balanceVar'" == "mean_clinic_pop" {
		drop if v1 == "Observations"
		}
		if     "`balanceVar'" == "mean_distance" {
		replace v1 = "Communities"         if  v1 == "Observations"
		}


		local    `balanceVar'_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/`balanceVar'_balance_``balanceVar'_fileNum'.tex") ///
		replace tex nohead noauto

	restore
	}


* **************************************************************************** *
* Prepare Final Table
* **************************************************************************** *

	cap  file close _all


	local BalanceTables =  " listing followup agecard quality_card good_memory mean_distance  " + ///
	" mean_clinic_pop bcg_pretrend penta1_pretrend penta2_pretrend "


	foreach level of local BalanceTables {

		* Remove lines from `dataout` export
		foreach lineToRemove in "\BSdocumentclass[]{article}"			///
		"\BSsetlength{\BSpdfpagewidth}{8.5in}" 	///
		"\BSsetlength{\BSpdfpageheight}{11in}"  ///
		"\BSbegin{document}" 				       	///
		"\BSend{document}" 					     	///
		"\BSbegin{tabular}{lcccccccc}"			///
		"Variable"								///
		"\BShline"								///
		"\BSend{tabular}"						{

		filefilter "${Replicate_SocialSignals_ATables}/`level'_balance_``level'_fileNum'.tex"      ///
		"${Replicate_SocialSignals_ATables}/`level'_balance_`=``level'_fileNum'+1'.tex" ///
		, from("`lineToRemove'") to("") replace
		erase	     "${Replicate_SocialSignals_ATables}/`level'_balance_``level'_fileNum'.tex"

		local `level'_fileNum = ``level'_fileNum' + 1
		}

		* Add incipit and end of LaTeX table
		*(to be directly input in TeX document) without further formatting
		file open  `level'File													///
		using "${Replicate_SocialSignals_ATables}/`level'_balance_``level'_fileNum'.tex"               ///
		, text read

		* Loop over lines of the original TeX file and save everything in a local
		local 	   `level'File ""
		file read  `level'File line
		while r(eof) == 0 {
		local 	  `level'File  " ``level'File' `line' "
		file read `level'File line
		}
		file close `level'File

		* Erase original file
		erase "${Replicate_SocialSignals_ATables}/`level'_balance_``level'_fileNum'.tex"

	}


	dis "`listingFile'"
	dis "`followupFile'"
	dis "`agecardFile'"
	dis "`quality_cardFile'"
	dis "`good_memoryFile'"
	dis "`mean_distanceFile'"
	dis "`mean_clinic_popFile'"
	dis "`bcg_pretrendFile'"
	dis "`penta1_pretrendFile'"
	dis "`penta2_pretrendFile'"


	* Make final table
	file  open finalFile using "${Replicate_SocialSignals_ATables}/baltab_listingsample.tex"	///
	, text write replace

	#d	;

	file write finalFile
	"                                      & \multicolumn{1}{c}{(1)}                 & \multicolumn{1}{c}{(2)}               & \multicolumn{1}{c}{(3)}               & \multicolumn{1}{c}{(4)}                & \multicolumn{1}{c}{(5)}                 & \multicolumn{1}{c}{(6)}               & \multicolumn{1}{c}{(7)}  & \multicolumn{1}{c}{(8)}  \\"    _n      ///
	"                                       &                                        & \multicolumn{6}{c}{\textbf{t-test differences}}    & \multicolumn{1}{c}{}  \\"    _n   ///
	"                                       & \multicolumn{1}{c}{\textbf{Control}}   & \multicolumn{6}{c}{\textbf{[p-value]}}             & \multicolumn{1}{c}{}  \\"    _n   ///
	"\multicolumn{1}{l}{\textbf{Variable}}  & \multicolumn{1}{c}{\textbf{Mean/(SE)}} & \multicolumn{1}{c}{\textbf{(C)-(UI)}} & \multicolumn{1}{c}{\textbf{(C)-(S4)}} &  \multicolumn{1}{c}{\textbf{(C)-(S5)}} & \multicolumn{1}{c}{\textbf{(UI)-(S4)}} & \multicolumn{1}{c}{\textbf{(UI)-(S5)}} & \multicolumn{1}{c}{\textbf{(S4)-(S5)}} & \multicolumn{1}{c}{\textbf{F-Test}} \\ \hline \\[-2ex]"    _n    ///
	"\multicolumn{9}{l}{\textbf{\textit{Panel A: Sample Definition}}}									  	 \\ [0.5ex]  " _n
	"\addlinespace[0.75ex] `listingFile' 																				      [-2ex]   " _n
	" `followupFile' 																						                   \\ [-2ex]   " _n
	"\multicolumn{9}{l}{\textbf{\textit{Panel B: Sample Characteristics}}}				 \\ [0.5ex]  " _n
	"\addlinespace[0.75ex] `agecardFile' 													  [-2ex]  " _n
	" `quality_cardFile' 																			  	  [-2ex]  " _n
	" `good_memoryFile' 																				    [-2ex]  " _n
	" `mean_distanceFile' 																				  [-2ex]  " _n
	" `mean_clinic_popFile' 																		 \\ [-2ex]  " _n
	"\multicolumn{9}{l}{\textbf{\textit{Panel C: Pre-trends in vaccination outcomes}}}	 \\ [0.5ex] " _n
	"\addlinespace[0.75ex] `bcg_pretrendFile' 										  [-2ex]  " _n
	"\addlinespace[0.75ex] `penta1_pretrendFile' 									  [-2ex]  " _n
	"\addlinespace[0.75ex] `penta2_pretrendFile' 								    [-2ex]  " _n
	"																													      \hline \hline \\ [-2ex] "
	;
	#d	cr

	file close finalFile


	* ******************************************************************************
	* End of the Dofile !!!
	* ******************************************************************************
